package com.ry.est.controller;

import com.alipay.api.AlipayApiException;
import com.ry.est.common.controller.BaseController;
import com.ry.est.service.PayService;
import com.ry.est.service.impl.ALiPayServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

/**
 * @author ry
 * @since 2021-11-16 11:53
 **/
@RestController
public class PayController extends BaseController {
    @Autowired
    private PayService payService;

    private static final Logger LOGGER = LoggerFactory.getLogger(PayController.class);

    /**
     * 获取支付宝支付页面
     * @param orderNo
     * @throws Exception
     */
    @GetMapping("/api/pay/aliPay")
    public void aliPay(String orderNo) throws Exception{
        String result = payService.paySubscription(orderNo);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(result);
    }

    /**
     * 支付宝服务器的异步回调接口，更新订单状态
     * @param params
     * @throws IOException
     * @throws AlipayApiException
     */
    @PostMapping("/api/pay/aliPay/notify")
    public void aliPayNotify(@RequestParam Map<String,String> params) throws IOException, AlipayApiException {
        LOGGER.info("异步回调参数"+params);
        String result = payService.aliPayNotify(params);
        response.getWriter().write(result);
    }

    /**
     * 支付宝同步回调接口
     * @param params
     * @throws AlipayApiException
     * @throws IOException
     */
    @GetMapping("/api/pay/aliPay/return")
    public void aliPayReturn(@RequestParam Map<String,String> params)
            throws AlipayApiException, IOException {
        LOGGER.info("同步回调参数:{}",params);
        //不作具体的业务操作
        //只是简单验证请求是否是支付宝发送的
        //验证成功之后，就让浏览器重定向到预约成功的界面
        boolean signVerified = payService.isSignVerified(params);
        //true就让浏览器重定向到预约成功的界面
        if (signVerified == true){
            response.sendRedirect("http://localhost:8081/confirmation");
        }else{
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("非法请求");
        }
        //false返回非法请求的页面
    }

}
